using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using OneNote = Microsoft.Office.Interop.OneNote;

namespace Webber
{
    [ComImport, Guid("C9590Fa7-2132-47fb-9a78-af0bf19af4e6")]
    public interface IOneNoteAddIn
    {
        bool OnClick([In] string strActivePageID);
        bool OnEvent([In] OneNote.OneNoteAddIn_Event evt, [In] String strParameter);
    }

    // dtse - switching to DLL class library
    /*
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    */
    
    [Guid("69a6aeb0-28b3-11db-a98b-0800200c9a66")]
    public class Webber : IOneNoteAddIn
    {
        public Webber()
        {
        }

        public bool OnClick([In] String strActivePageID)
        {

            ThreadStart ts = new ThreadStart(createAndRun);
            Thread t = new Thread(ts);
            t.Start();

            return true;
        }

        private void createAndRun()
        {

            // find window
            IntPtr hWnd = FindWindow(null, "OneNote Web Exporter");

            // if found, bring to front
            if (hWnd != IntPtr.Zero)
            {
                ShowWindowAsync(hWnd, 1 );// 1=WS_SHOWNORMAL
                SetForegroundWindow(hWnd);
            }
            else
            {
                Application.Run(new Form1());
                GC.Collect();
            }
        }

        public bool OnEvent([In] OneNote.OneNoteAddIn_Event evt, [In] String strParameter)
        {
            return true;
        }

        [DllImport("User32", EntryPoint = "FindWindow")]
        static extern IntPtr FindWindow(string className, string windowName);

        [DllImport("User32", EntryPoint = "SetForegroundWindow")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);

        [DllImport("User32", EntryPoint = "SetForegroundWindow")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
    }

}